package alejandro.castro.asteroid.components;

import java.util.Random;

import alejandro.castro.collidables.Collidable;
import alejandro.castro.collidables.CollidableCircle;

import com.uqbar.vainilla.DeltaState;
import com.uqbar.vainilla.appearances.Sprite;

public class Asteroid extends Collidable {


	public final double MAXANGLE = Math.PI * 2;
	private double currentAngle;
	private double rotateCoefficient;
	private double xMove;
	private double yMove;
	private final static double RATIO = 48;
	

	private Sprite appearance;

	public Asteroid(double x, double y, double xMove, double yMove) {
		super(x-RATIO, y-RATIO);
		initialize(xMove, yMove);
	}

	private void initialize(double xMove, double yMove) {
		Random random = new Random();
		//variable speed
		double speed = random.nextDouble() * 25 + 25; // between 25 and 50
		this.xMove = xMove * speed;
		this.yMove = yMove * speed;
		this.currentAngle = random.nextDouble() * MAXANGLE;
		this.rotateCoefficient = random.nextDouble() * MAXANGLE - Math.PI;
		setAsteroidSprite(random.nextInt(3));
	}

	private void setAsteroidSprite(int indexSprite) {
		this.appearance = Sprite.fromImage("/images/ast_a_" + indexSprite + ".png");
		this.setAppearance(appearance);
	}

	@Override
	public void update(DeltaState deltaState) {
		super.update(deltaState);		
		this.rotate(deltaState.getDelta());
		this.move(deltaState.getDelta()*xMove, deltaState.getDelta()*yMove);
	}

	private void rotate(double delta) {
		this.updateAngle(delta);
		this.setAppearance(this.appearance.rotate(this.currentAngle));
	}

	private void updateAngle(double delta) {
		this.currentAngle += delta * rotateCoefficient;
		if(currentAngle > Math.PI){
			currentAngle = currentAngle % MAXANGLE;
		}
		if(currentAngle < 0){
			currentAngle = currentAngle % MAXANGLE + MAXANGLE;
		}
	}

	@Override
	public void initCollidableBehavior() {
		this.addColidableShape(new CollidableCircle(this, RATIO, RATIO, 40));
	}

	@Override
	public double getWidth() {
		return RATIO * 2;
	}

	@Override
	public double getHeight() {
		return RATIO * 2;
	}

	public void hasBeenDestroyed() {
		this.getScene().addAsteroid(new Asteroid(getX(), getY(), xMove, yMove));
		
	}


	
}
